<template>
  <div>
    <!--搜索框-->
    <el-form :inline="true" :model="searchForm">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="读者姓名" clearable @clear="getList"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="select">搜索</el-button>
        <el-button type="primary" @click="saveHandle" v-if="hasAuth('reader:manage:save')">新增</el-button>
        <el-popconfirm title="确定要删除这些记录吗？" @confirm="delHandle(null)" style="margin-left: 10px;"
                       v-if="hasAuth('reader:manage:delete')">
          <el-button type="danger" slot="reference" :disabled="delBtnStu">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table ref="multipleTable" border stripe :data="tableData" tooltip-effect="dark" style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column width="50px" type="selection"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="name" label="读者姓名"></el-table-column>
      <el-table-column width="50px" label="性别">
        <template slot-scope="scope">
          <span v-if="scope.row.sex === 1">男</span>
          <span v-if="scope.row.sex === 0">女</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" prop="affiliatedUnit" label="所属单位"></el-table-column>
      <el-table-column width="160px" prop="createTime" label="创建日期"></el-table-column>
      <el-table-column width="170px" prop="idCard" label="身份证号"></el-table-column>
      <el-table-column width="130px" prop="birthday" label="出生日期"></el-table-column>
      <el-table-column width="80px" prop="borrowCount" label="借阅数量"></el-table-column>
      <el-table-column width="100px" prop="returnCount" label="已归还数量"></el-table-column>
      <el-table-column width="100px" label="操作" v-if="hiddenTableCol">
        <template slot-scope="scope">
          <el-button type="text" @click="editHandle(scope.row.id)" v-if="hasAuth('reader:manage:update')">编辑
          </el-button>
          <el-divider direction="vertical" v-if="hasAuth('reader:manage:delete')&&pagePerms.length>1"></el-divider>
          <el-popconfirm title="确定要删除这条记录吗？" @confirm="delHandle(scope.row.id)" v-if="hasAuth('reader:manage:delete')">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--页码-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current"
                   :page-sizes="[10, 20, 50, 100]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
                   :total="total"></el-pagination>

    <el-dialog title="读者信息" :visible.sync="dialogFormVisible" width="600px">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="用户名" prop="userId" label-width="100px">
          <el-select v-model="editForm.userId" filterable placeholder="请输入并选择用户名">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.username"
                :value="item.id">
            </el-option>
          </el-select>
          <el-alert title="读者与用户一一对应，应选择数据库中已存在的用户" :closable="false" type="info" style="line-height: 12px;"></el-alert>
        </el-form-item>
        <el-form-item label="读者姓名" prop="name" label-width="100px">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex" label-width="100px">
          <el-radio-group v-model="editForm.sex">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属单位" prop="affiliatedUnit" label-width="100px">
          <el-input v-model="editForm.affiliatedUnit" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard" label-width="100px">
          <el-input v-model="editForm.idCard" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday" label-width="100px">
          <el-input v-model="editForm.birthday" type="date" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="isUpdate" label="借阅数量" prop="borrowCount" label-width="100px">
          <el-input v-model="editForm.borrowCount" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="isUpdate" label="已归还数量" prop="returnCount" label-width="100px">
          <el-input v-model="editForm.returnCount" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import qs from "qs";

export default {
  name: "Type",
  data() {
    return {
      //是否是更新
      isUpdate: false,
      //搜索框表单
      searchForm: {name: null},
      //编辑表单
      editForm: {},
      //编辑表单规则
      editFormRules: {
        userId: [{required: true, message: '请选择用户名', trigger: 'blur'}],
        name: [{required: true, message: '请输入读者姓名', trigger: 'blur'}],
        sex: [{required: true, message: '请选择读者性别', trigger: 'blur'}],
        idCard: [{required: true, message: '请输入身份证号', trigger: 'blur'}],
      },
      //当前页，默认为1
      current: 1,
      //记录总数，默认为0
      total: 0,
      //每页记录数，默认每页10条
      size: 10,
      //是否显示编辑/新增dialog
      dialogFormVisible: false,
      //表格数据
      tableData: [],
      //当前页需要的权限列表，只包括按钮类型
      pagePerms: [],
      //隐藏表格操作类
      hiddenTableCol: false,
      //选中的行数组
      multipleSelection: [],
      //是否选择记录，如果否则禁用批量删除按钮
      delBtnStu: true,
      options: [],
      userId: null,
    }
  },
  methods: {
    select() {
      this.current = 1;
      this.getList();
    },
    saveHandle() {
      this.isUpdate = false;
      this.resetForm('editForm');
      this.$axios.get('/sys/user/list').then(res => {
        this.options = res.data.data;
      });
      this.dialogFormVisible = true;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      this.delBtnStu = rows.length === 0
    },
    getList() {
      this.$axios.get('/reader', {
        params: {
          name: this.searchForm.name,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getList()
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          let param = this.editForm;
          if (this.editForm.id && this.userId===this.editForm.userId) {
            param.userId = null;
          }
          this.$axios({
            method: this.editForm.id ? 'put' : 'post',
            url: '/reader',
            data: param
          }).then(res => {
            loading.close();
            this.resetForm(formName)
            this.$message({
              showClose: true, message: '恭喜你，操作成功', type: 'success', duration: 2000, onClose: () => {
                this.getList()
              }
            });
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editHandle(id) {
      this.isUpdate = true;
      this.resetForm('editForm');
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$axios.get('/sys/user/list').then(res => {
        this.options = res.data.data;
      });
      this.$axios.get("/reader/info/" + id).then(res => {
        loading.close();
        this.editForm = res.data.data
        this.userId = res.data.data.userId
        this.dialogFormVisible = true
      })
    },
    delHandle(id) {
      let ids = []
      id ? ids.push(id) : this.multipleSelection.forEach(row => {
        ids.push(row.id)
      })

      this.$axios.delete("/reader", {
        params: {
          ids: ids,
        },
        paramsSerializer: params => {
          return qs.stringify(params, {indices: false})
        }
      }).then(res => {
        this.$message({
          showClose: true, message: '恭喜你，操作成功', type: 'success', duration: 2000, onClose: () => {
            this.getList()
          }
        });
      })
    },
    resetForm(formName) {
      this.dialogFormVisible = false
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.editForm = {}
    },
  },
  created() {
    this.getList();
    this.hiddenTableCol = this.hasAuth('reader:manage:update') || this.hasAuth('reader:manage:delete')
    this.pagePerms = this.getPagePerms(this.$route.name);
  }
}
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 20px;
  padding-bottom: 30px;
}

.drawer-p {
  margin-left: 20px;
}
</style>
